package com.ww.springboot.dd.controller;


import cn.hutool.http.HttpRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩包下载功能
 *
 * @author youfan
 * @date 2022-12-02
 */
public class ZipUtil {

    /**
     * 将文件压缩成压缩包并下载
     *
     * @param files
     */
    public static void zip(String[] files) throws FileNotFoundException {

        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos));
        try {
             byte[] buf = new byte[8192];
            int len;
            // 遍历数组中的数据

            String imageUrl = "http://image.izehui.com/CPMS/20231216/13ed3288902b6486290bc4df43732c91.jpg";
            byte[] bytes = HttpRequest.get(imageUrl).execute().bodyBytes();
            // 自定义压缩的名称
            ZipEntry ze = new ZipEntry("13ed3288902b6486290bc4df43732c91" + "(" + 1 + ").jpg");
            zos.putNextEntry(ze);
            bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
                // 判断流中的数据不为0将文件添加到压缩包
                while ((len = bis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
            zos.write(bytes, 0, bytes.length);

            System.out.println(baos.toByteArray().length);
            zos.closeEntry();
            System.out.println(baos.toByteArray().length);
            zos.finish();
            System.out.println(baos.toByteArray().length);
            zos.flush();
            System.out.println(baos.toByteArray().length);
            //zos.closeEntry();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (zos != null) {
                try {
                    zos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        String[] files = new String[]{
                "D:\\MyFile\\ZJ00014\\zj014\\Desktop\\test\\03314\\123.jpg"
        };
        try {
            zip(files);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
 